package scope

import (
	"fmt"
	"ia/common/storage"
	"ia/common/support/tools"

	"gorm.io/gorm"
)

// https://gorm.io/zh_CN/docs/scopes.html
// GORM2的通用逻辑

// 通用（软删除）操作。只能放到最后调用
//func SoftDelete(model interface{}, ids []int64, uid uint) func(db *gorm.DB) *gorm.DB {
//	return func(db *gorm.DB) *gorm.DB {
//		return db.Model(model).
//			Where("id in (?)", ids).
//			Updates(map[string]interface{}{
//				"DeletedTime": tools.CurrentTimeString(),
//				"DeleterId":   uid,
//			})
//	}
//}
func SoftDelete(model interface{}, ids []int64, uid uint) error {
	return storage.GDB1.Model(model).Where("id in (?)", ids).
		Updates(map[string]interface{}{
			"DeletedTime": tools.CurrentTimeString(),
			"DeleterId":   uid,
		}).Error
	//return func(db *gorm.DB) *gorm.DB {
	//	return db.Model(model).
	//		Where("id in (?)", ids).
	//		Updates(map[string]interface{}{
	//			"DeletedTime": tools.CurrentTimeString(),
	//			"DeleterId":   uid,
	//		})
	//}
}

// 根据ID更新单记录
func UpdateOne(model interface{}, id uint) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		return db.Model(model).
			//Omit("creator_id", "created_time", "deleter_id", "deleted_time").
			Where("id in (?)", id)
	}
}

// 不含软删的数据
func Scope(db *gorm.DB) *gorm.DB {
	return db.Where("deleted_time IS NULL")
}

func In(idList []int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		return db.Where("id IN (?)", idList)
	}
}

func LikeOfAround(v interface{}) string {
	return "%" + fmt.Sprintf("%v", v) + "%"
}
func LikeOfPre(v interface{}) string {
	return "%" + fmt.Sprintf("%v", v)
}
func LikeOfPost(v interface{}) string {
	return fmt.Sprintf("%v", v) + "%"
}
